//
//  SGFocusImageFrame.m
//  ScrollViewLoop
//
//  Created by Vincent Tang on 13-7-18.
//  Copyright (c) 2013年 Vincent Tang. All rights reserved.
//

#import "SGFocusImageFrame.h"
#import "SGFocusImageItem.h"
#import <objc/runtime.h>
#import "UIView+Extension.h"
#define ITEM_WIDTH SCREEN_WIDTH

@interface SGFocusImageFrame () {
    UIScrollView *_scrollView;
    //    GPSimplePageView *_pageControl;
    UIPageControl *_pageControl;
    UILabel *_titleLabel;
    BOOL canScroll;
    NSMutableArray *imageArray;
    
}

- (void)setupViews;
- (void)switchFocusImageItems;
@end

static NSString *SG_FOCUS_ITEM_ASS_KEY = @"loopScrollview";

//static CGFloat SWITCH_FOCUS_PICTURE_INTERVAL = 2.0; //switch interval time

@implementation SGFocusImageFrame
@synthesize delegate = _delegate;

- (id)initWithFrame:(CGRect)frame delegate:(id<SGFocusImageFrameDelegate>)delegate focusImageItems:(SGFocusImageItem *)firstItem, ...
{
    self = [super initWithFrame:frame];
    if (self) {
        NSMutableArray *imageItems = [NSMutableArray array];
        SGFocusImageItem *eachItem;
        va_list argumentList;
        if (firstItem)
        {
            [imageItems addObject: firstItem];
            va_start(argumentList, firstItem);
            while((eachItem = va_arg(argumentList, SGFocusImageItem *)))
            {
                [imageItems addObject: eachItem];
            }
            va_end(argumentList);
        }
        
        objc_setAssociatedObject(self, (const void *)SG_FOCUS_ITEM_ASS_KEY, imageItems, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        _isAutoPlay = YES;
        [self setupViews];
       
        [self setDelegate:delegate];
    }

    return self;
}

- (id)initWithFrame:(CGRect)frame delegate:(id<SGFocusImageFrameDelegate>)delegate imageItems:(NSArray *)items isAuto:(BOOL)isAuto isShowTitle:(BOOL)isShow isShowCurrentIndex:(BOOL)showIndex
{
    self = [super initWithFrame:frame];
    if (self)
    {
//        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(stopScroll) name:@"stopImageScroll" object:nil];
//        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(startScroll) name:@"startImageScroll" object:nil];
        
        
        NSMutableArray *imageItems = [NSMutableArray arrayWithArray:items];
        objc_setAssociatedObject(self, (const void *)SG_FOCUS_ITEM_ASS_KEY, imageItems, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        _isAutoPlay = isAuto;
        _isShowTitle = isShow;
        _isShowIndex = showIndex;
        [self setupViews];
        [self setDelegate:delegate];
        canScroll = YES;
    }
    
    return self;
}



- (void)dealloc
{
    objc_setAssociatedObject(self, (const void *)SG_FOCUS_ITEM_ASS_KEY, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    _scrollView.delegate = nil;
//    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"stopImageScroll" object:nil];
//    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"startImageScroll" object:nil];
    
    [_scrollView release];
    if (_pageControl) {
       [_pageControl release];
    }
    [super dealloc];
}

#pragma mark - private methods
- (void)setupViews
{
    NSArray *imageItems = objc_getAssociatedObject(self, (const void *)SG_FOCUS_ITEM_ASS_KEY);
    _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
    _scrollView.scrollsToTop = NO;

    //    _pageControl = [[GPSimplePageView alloc] initWithFrame:CGRectMake(self.bounds.size.width *.5 - size.width *.5, self.bounds.size.height - size.height, size.width, size.height)];
    
//    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(260, self.frame.size.height -20, 60, 10)];
//    _pageControl.currentPageIndicatorTintColor = [UIColor redColor];
//    _pageControl.pageIndicatorTintColor = [UIColor whiteColor];
//    _pageControl.backgroundColor = [UIColor clearColor];
//    _pageControl.userInteractionEnabled = NO;
    [self addSubview:_scrollView];
//    [self addSubview:_pageControl];
    
   
    if (!_isShowIndex) {
        _pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake((SCREEN_WIDTH-120)/2, self.bottom-25, 120, 10)];
       // NSInteger num = imageItems.count > 1 ? imageItems.count-2:imageItems.count;
        _pageControl.numberOfPages = 2;
        
        _pageControl.hidesForSinglePage=YES;
        
        _pageControl.currentPage = 0;
        //_pageControl.pageIndicatorTintColor = CustomliaotianLabelColor;
        _pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
        _pageControl.backgroundColor = [UIColor clearColor];
        _pageControl.userInteractionEnabled = NO;
        [self addSubview:_pageControl];
        
        [self bringSubviewToFront:_pageControl];
    }


    /*
     _scrollView.layer.cornerRadius = 10;
     _scrollView.layer.borderWidth = 1 ;
     _scrollView.layer.borderColor = [[UIColor lightGrayColor ] CGColor];
     */
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.pagingEnabled = YES;
    _scrollView.delegate = self;
    
    // single tap gesture recognizer
    UITapGestureRecognizer *tapGestureRecognize = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureRecognizer:)];
    tapGestureRecognize.delegate = self;
    tapGestureRecognize.numberOfTapsRequired = 1;
    [_scrollView addGestureRecognizer:tapGestureRecognize];
    [tapGestureRecognize release];

    //objc_setAssociatedObject(self, (const void *)SG_FOCUS_ITEM_ASS_KEY, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self addImageViews:imageItems];
}

-(UIImage *)heheWithImage:(UIImage *)aImage{
    
    CGRect myImageRect = CGRectMake(0, 0, 10, 10);
    
    CGImageRef cgimg = CGImageCreateWithImageInRect(aImage.CGImage, myImageRect);
    UIImage *cjImage = [UIImage imageWithCGImage:cgimg];
    CGImageRelease(cgimg);//用完一定要释放，否则内存泄露
    return cjImage;
    
}

#pragma mark 根据图片的个数添加子视图
-(void)addImageViews:(NSArray *)aImageItems{
    //移除子视图
    for (UIView *lView in _scrollView.subviews) {
        [lView removeFromSuperview];
    }

    NSInteger num = aImageItems.count > 1 ? aImageItems.count-2:aImageItems.count;

    if (_isShowIndex) {
         
         imageArray = [NSMutableArray array];
         for (int i = 0; i < (int)num; i++) {
             UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(299-16*i, self.bottom-15, 11, 3)];
            // imgView.contentMode = UIViewContentModeScaleAspectFit;
             imgView.image = [UIImage imageNamed:@"pic_037"];
             //    imageV.backgroundColor = RGBColor(223, 230, 230);
           //  imgView.backgroundColor = [UIColor colorWithPatternImage:[self heheWithImage:[UIImage imageNamed:@"pic_037"]]];
             [imageArray addObject:imgView];
             
             
             [self addSubview:imgView];
             
             
         }
         
         [imageArray retain];

        
        
    }else{
        
        _pageControl.numberOfPages = num;

    }
    float space = 0;
    CGSize size = CGSizeMake(SCREEN_WIDTH, 0);
    for (int i = 0; i < aImageItems.count; i++) {
        SGFocusImageItem *item = [aImageItems objectAtIndex:i];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * _scrollView.frame.size.width+space, space, _scrollView.frame.size.width-space*2, _scrollView.frame.size.height-2*space-size.height)];
        //加载图片

        if ([item.image hasPrefix:@"http"]) {
           // imageView.contentMode = UIViewContentModeScaleAspectFit;
            //    imageV.backgroundColor = RGBColor(223, 230, 230);
            imageView.backgroundColor = [UIColor colorWithPatternImage:[self heheWithImage:[UIImage imageNamed:@"pic_037"]]];

//            [imageView setImageWithURL:[NSURL URLWithString:item.image] placeholderImage:[UIImage imageNamed:@"pic_037"]];
            
            
            [imageView sd_setImageWithURL:[NSURL URLWithString:item.image] placeholderImage:[UIImage imageNamed:@"pic_037"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                
                //imageView.contentMode = UIViewContentModeScaleToFill;
            }];
            
        }else{
            imageView.image = [UIImage imageNamed:item.image];
            
           // imageView.contentMode = UIViewContentModeScaleAspectFit;
            imageView.image = [UIImage imageNamed:item.image];
            //    imageV.backgroundColor = RGBColor(223, 230, 230);
            imageView.backgroundColor = [UIColor colorWithPatternImage:[self heheWithImage:[UIImage imageNamed:item.image]]];
        }
        
        [_scrollView addSubview:imageView];
        [imageView release];
        
        
        if (_isShowTitle) {
            UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, _scrollView.height-30, self.width, 30)];
            view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
            [imageView addSubview:view];
            [view release];
            _titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, _scrollView.height-30, self.width-10-69, 30)];
            _titleLabel.font = [UIFont boldSystemFontOfSize:13];
            _titleLabel.textColor = [UIColor whiteColor];
            _titleLabel.text = item.title;
            _titleLabel.backgroundColor = [UIColor clearColor];
            [imageView addSubview:_titleLabel];
            [_titleLabel release];
        }
    }
    
    _scrollView.contentSize = CGSizeMake(_scrollView.frame.size.width * aImageItems.count, _scrollView.frame.size.height);
    
    if ([aImageItems count]>1)
    {
        [_scrollView setContentOffset:CGPointMake(ITEM_WIDTH, 0) animated:NO] ;
        if (_isAutoPlay)
        {
            [self performSelector:@selector(switchFocusImageItems) withObject:nil afterDelay:_timeDurition];
        }
    }
}

#pragma mark 改变添加视图内容
-(void)changeImageViewsContent:(NSArray *)aArray{
    NSMutableArray *imageItems = [NSMutableArray arrayWithArray:aArray];
    objc_setAssociatedObject(self, (const void *)SG_FOCUS_ITEM_ASS_KEY, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    objc_setAssociatedObject(self, (const void *)SG_FOCUS_ITEM_ASS_KEY, imageItems, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self addImageViews:imageItems];
}

- (void)switchFocusImageItems
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(switchFocusImageItems) object:nil];
    
    CGFloat targetX = _scrollView.contentOffset.x + _scrollView.frame.size.width;
    NSArray *imageItems = objc_getAssociatedObject(self, (const void *)SG_FOCUS_ITEM_ASS_KEY);
    targetX = (int)(targetX/ITEM_WIDTH) * ITEM_WIDTH;
    [self moveToTargetPosition:targetX];
    
    if ([imageItems count]>1 && _isAutoPlay)
    {
        [self performSelector:@selector(switchFocusImageItems) withObject:nil afterDelay:_timeDurition];
    }
    
}

- (void)singleTapGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
{
    NSLog(@"%s", __FUNCTION__);
    NSArray *imageItems = objc_getAssociatedObject(self, (const void *)SG_FOCUS_ITEM_ASS_KEY);
    int page = (int)(_scrollView.contentOffset.x / _scrollView.frame.size.width);
    if (page > -1 && page < imageItems.count) {
        SGFocusImageItem *item = [imageItems objectAtIndex:page];
        if ([self.delegate respondsToSelector:@selector(foucusIndex:didSelectItem:)]) {
            [self.delegate foucusIndex:page didSelectItem:item];
        }
    }
}

- (void)moveToTargetPosition:(CGFloat)targetX
{
    BOOL animated = YES;
    //    NSLog(@"moveToTargetPosition : %f" , targetX);
    if (canScroll) {
       [_scrollView setContentOffset:CGPointMake(targetX, 0) animated:animated];
    }
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    float targetX = scrollView.contentOffset.x;
    NSArray *imageItems = objc_getAssociatedObject(self, (const void *)SG_FOCUS_ITEM_ASS_KEY);
    if ([imageItems count]>=3)
    {
        if (targetX >= ITEM_WIDTH * ([imageItems count] -1)) {
            targetX = ITEM_WIDTH;
            [_scrollView setContentOffset:CGPointMake(targetX, 0) animated:NO];
        }
        else if(targetX <= 0)
        {
            targetX = ITEM_WIDTH *([imageItems count]-2);
            [_scrollView setContentOffset:CGPointMake(targetX, 0) animated:NO];
        }
    }
    NSInteger page = (_scrollView.contentOffset.x+ITEM_WIDTH/2.0) / ITEM_WIDTH;
   
    if (_isShowIndex) {
        for (int i = 0; i < imageArray.count; i ++) {
            UIImageView *imgView = (UIImageView *)imageArray[imageArray.count-1-i];
            if (i+1 == page) {
                imgView.image = [UIImage imageNamed:@"banner-btn"];
            }else{
                imgView.image = [UIImage imageNamed:@"banner-btn2"];
            }
        }
    }else{
        
        if ([imageItems count] > 1)
        {
            page --;
            if (page >= _pageControl.numberOfPages)
            {
                page = 0;
            }else if(page <0)
            {
                page = _pageControl.numberOfPages -1;
            }
        }
        
        _pageControl.currentPage = page;
    }
   
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (!decelerate)
    {
        CGFloat targetX = _scrollView.contentOffset.x + _scrollView.frame.size.width;
        targetX = (int)(targetX/ITEM_WIDTH) * ITEM_WIDTH;
        [self moveToTargetPosition:targetX];
    }
}

- (void)scrollToIndex:(int)aIndex
{
    NSArray *imageItems = objc_getAssociatedObject(self, (const void *)SG_FOCUS_ITEM_ASS_KEY);
    if ([imageItems count]>1)
    {
        if (aIndex >= (int)([imageItems count]-2))
        {
            aIndex = (int)([imageItems count]-3);
        }
        [self moveToTargetPosition:ITEM_WIDTH*(aIndex+1)];
    }else
    {
        [self moveToTargetPosition:0];
    }
    [self scrollViewDidScroll:_scrollView];
    
}
@end